package com.simen.downloader.model;

import com.simen.downloader.util.AppLog;

import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * Created by zhangming on 16/5/16.
 */
public class BooleanHolder {
    private volatile boolean flag;
    final ReentrantReadWriteLock lock;
    final ReentrantReadWriteLock.WriteLock writeLock;
    final ReentrantReadWriteLock.ReadLock readLock;

    public BooleanHolder(boolean flag) {
        this.flag = flag;
        this.lock = new ReentrantReadWriteLock(true);
        this.writeLock = this.lock.writeLock();
        this.readLock = this.lock.readLock();
    }

    public BooleanHolder() {
        this.lock = new ReentrantReadWriteLock(true);
        this.writeLock = this.lock.writeLock();
        this.readLock = this.lock.readLock();
    }

    public boolean get() {
        return flag;
    }

    public void set(boolean status) {
        if (this.lock.isWriteLocked()) {
            AppLog.dLog("ReentrantReadWriteLock has been locked");
            return;
        }
        AppLog.dLog("try to get the writeLock " + status);
        this.writeLock.lock();
        this.flag = status;
        this.writeLock.unlock();
    }

    public ReentrantReadWriteLock.ReadLock getReadLock() {
        return readLock;
    }

}
